package com.seguriapp.common.config;

import java.io.InputStream;
import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class InitServiceImpl {

  private static final String CONFIG_FILE_NAME = "config-file.xml";
  private static final String METHOD_INSTANCE = "getInstance";
  private static final Logger logger = Logger.getLogger(InitServiceImpl.class);

  public InitServiceImpl() {
    Serializer serializer = new Persister();
    try {
      final Method method = Class.forName(GlobalConfigLoader.class.getName()).getMethod(METHOD_INSTANCE, new Class[0]);
      GlobalConfigLoader globalConfigLoader = (GlobalConfigLoader) method.invoke(null, new Object[0]);
      globalConfigLoader.init(serializer.read(GlobalConfig.class, toInputStream(CONFIG_FILE_NAME)));
    } catch (Exception e) {
      logger.error("error al cargar el archivo de configuracion".concat(e.getMessage()));
      e.printStackTrace();
    }
  }

  /**
   * Convierte un String en InputStream
   */
  private InputStream toInputStream(final String name) {
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    return loader.getResourceAsStream(name);
  }
}
